import React from 'react';
import { useAuthStore } from '@/store/auth';
import { useUserStore } from '@/store/user';
import { flattenMenus } from '@/utils/dynamicRoutes';

// 用户权限信息类型
export interface UserPermission {
  userId: string | number;
  username: string;
  menus: any[];
  permissions: string[];
  roles: string[];
}

// 使用用户权限的Hook
export const usePermission = () => {
  const { isAuthenticated, token } = useAuthStore();
  const {
    permissions: permissionData,
    isLoading: permissionLoading,
    getUserPermissions: fetchUserPermissions,
    refreshPermissions
  } = useUserStore();

  // 获取用户权限信息（使用缓存）
  React.useEffect(() => {
    console.log('[usePermission] 权限获取触发:', { isAuthenticated, token });
    if (isAuthenticated && token) {
      fetchUserPermissions()
        .then(data => {
          console.log('[usePermission] 权限获取成功:', data);
        })
        .catch(error => {
          console.error('[usePermission] 权限获取失败:', error);
        });
    }
  }, [isAuthenticated, token, fetchUserPermissions]);

  // 检查是否有指定权限
  const hasPermission = (permission: string): boolean => {
    if (!permissionData) return false;
    return permissionData.permissions.includes(permission);
  };

  // 检查是否有任意一个权限
  const hasAnyPermission = (permissions: string[]): boolean => {
    if (!permissionData) return false;
    return permissions.some(permission => hasPermission(permission));
  };

  // 检查是否有所有权限
  const hasAllPermissions = (permissions: string[]): boolean => {
    if (!permissionData) return false;
    return permissions.every(permission => hasPermission(permission));
  };

  // 检查是否有指定角色
  const hasRole = (role: string): boolean => {
    if (!permissionData) return false;
    return permissionData.roles.includes(role);
  };

  // 检查是否有任意一个角色
  const hasAnyRole = (roles: string[]): boolean => {
    if (!permissionData) return false;
    return roles.some(role => hasRole(role));
  };

  // 获取用户菜单（树形结构）
  const getUserMenus = () => {
    if (!permissionData) return [];
    return permissionData.menus;
  };

  // 获取扁平化菜单列表
  const getFlatMenus = () => {
    if (!permissionData) return [];
    return flattenMenus(permissionData.menus);
  };

  // 获取用户权限列表
  const getUserPermissions = () => {
    if (!permissionData) return [];
    return permissionData.permissions;
  };

  // 获取用户角色列表
  const getUserRoles = () => {
    if (!permissionData) return [];
    return permissionData.roles;
  };

  return {
    permissionData,
    permissionLoading,
    permissionError: null,
    refetchPermission: refreshPermissions,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    hasRole,
    hasAnyRole,
    getUserMenus,
    getFlatMenus,
    getUserPermissions: () => permissionData?.permissions || [],
    getUserRoles: () => permissionData?.roles || [],
  };
};

// 权限指令组件类型
export interface PermissionGuardProps {
  permission?: string;
  permissions?: string[];
  roles?: string[];
  any?: boolean; // 是否满足任意一个即可
  fallback?: React.ReactNode;
  children: React.ReactNode;
}

// 权限守卫组件
export const PermissionGuard: React.FC<PermissionGuardProps> = ({
  permission,
  permissions,
  roles,
  any = false,
  fallback = null,
  children,
}) => {
  const {
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    hasRole,
    hasAnyRole,
  } = usePermission();

  // 检查单个权限
  if (permission && !hasPermission(permission)) {
    return React.createElement(React.Fragment, null, fallback);
  }

  // 检查多个权限
  if (permissions) {
    const hasPermissionAccess = any
      ? hasAnyPermission(permissions)
      : hasAllPermissions(permissions);

    if (!hasPermissionAccess) {
      return React.createElement(React.Fragment, null, fallback);
    }
  }

  // 检查角色
  if (roles) {
    const hasRoleAccess = any ? hasAnyRole(roles) : roles.every(role => hasRole(role));

    if (!hasRoleAccess) {
      return React.createElement(React.Fragment, null, fallback);
    }
  }

  return React.createElement(React.Fragment, null, children);
};

export default usePermission;